/*
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */

/*
 *
 *
 *
 *
 *
 * Written by Doug Lea with assistance from members of JCP JSR-166
 * Expert Group and released to the public domain, as explained at
 * http://creativecommons.org/publicdomain/zero/1.0/
 */

package java.util.concurrent.locks;
import java.util.concurrent.TimeUnit;
import java.util.Collection;

/**
 * ReadWriteLock的实现，支持与ReentrantLock类似的语义。
 * <p>这个类有以下属性:
 *
 * <ul>
 * <li><b>获取顺序</b>
 *
 * <p>这个类不会为锁访问强加读或写优先顺序。
 * 然而，它确实支持可选的公平策略。
 *
 * <dl>
 * <dt><b><i>默认 不公平模式</i></b>
 * <dd>当构造为Non-fair(默认)时，读和写锁的进入顺序是不指定的，受到重入的约束。
 * 持续竞争的非公平锁可能无限期地延迟一个或多个读线程或写线程，但通常会比公平锁具有更高的吞吐量。
 *
 * <dt><b><i>公平模式</i></b>
 * <dd>当构造为Fair时，线程使用近似到达顺序的策略竞争条目。
 * 当当前持有的锁被释放时，要么给等待时间最长的单个写线程分配写锁，
 * 要么给一组等待时间长于所有等待写线程的读线程分配读锁。
 *
 * <p>如果一个线程试图获得一个公平读锁(不可重入)，如果写锁被持有，或者有一个正在等待的写线程，那么这个线程将会阻塞。
 * 在当前最老的等待写线程获得并释放写锁之后，该线程才会获得读锁。
 * 当然，如果一个正在等待的写线程放弃了等待，留下一个或多个读线程作为队列中最长的等待线程，这些读线程将被分配读锁。
 *
 * <p>一个试图获取公平写锁(非重入)的线程将会阻塞，除非读锁和写锁都是空闲的(这意味着没有等待的线程)。
 * (注意，非阻塞的ReadLock.tryLock()和writellock.trylock()方法
 * 不接受这个公平设置，并且会在可能的情况下立即获取锁，而不管等待的线程是什么)。
 * <p>
 * </dl>
 *
 * <li><b>可重入性</b>
 *
 * <p>这个锁允许读取器和写入器以ReentrantLock的方式重新获取读或写锁。
 * 在写线程持有的所有写锁都被释放之前，不可重入的读线程是不允许的。
 *
 * <p>另外，写器可以获得读锁，反之不行。
 * 在其他应用程序中，当调用期间持有写锁或回调在读锁下执行读操作的方法时，可重入性可能很有用。
 * 如果读取器试图获取写锁，它将永远不会成功。
 *
 * <li><b>锁降级</b>
 * <p>可重入性还允许将写锁降级为读锁，方法是先获取写锁，然后获取读锁，然后释放写锁。
 * 但是，从读锁升级到写锁是不可能的。
 *
 * <li><b>锁获取中断</b>
 * <p>读锁和写锁都支持在锁定获取期间中断。
 *
 * <li><b>支持条件</b>
 * <p>就写锁而言，写锁提供的条件实现与ReentrantLock提供的条件实现的行为方式相同。
 * 对于ReentrantLock，则使用newCondition。当然，这个条件只能与写锁一起使用。
 *
 * <p>读锁不支持条件，readLock(). newCondition()抛出UnsupportedOperationException。

 *
 * <li><b>仪器</b>
 * <p>该类支持确定锁是持有还是争用的方法。
 * 这些方法是为了监视系统状态而设计的，而不是为了同步控制。
 * </ul>
 *
 * <p>该类的序列化行为与内置锁的行为相同:
 * 反序列化的锁处于解锁状态，而不管其序列化时的状态如何。
 *
 * <p>示例用法。下面是一个代码草图，展示了在更新缓存后如何执行锁降级
 * (以非嵌套方式处理多个锁时，异常处理尤其棘手):
 *
 * <pre> {@code
 * class CachedData {
 *   Object data;
 *   volatile boolean cacheValid;
 *   final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
 *
 *   void processCachedData() {
 *     rwl.readLock().lock();
 *     if (!cacheValid) {
 *       // Must release read lock before acquiring write lock
 *       rwl.readLock().unlock();
 *       rwl.writeLock().lock();
 *       try {
 *         // Recheck state because another thread might have
 *         // acquired write lock and changed state before we did.
 *         if (!cacheValid) {
 *           data = ...
 *           cacheValid = true;
 *         }
 *         // Downgrade by acquiring read lock before releasing write lock
 *         rwl.readLock().lock();
 *       } finally {
 *         rwl.writeLock().unlock(); // Unlock write, still hold read
 *       }
 *     }
 *
 *     try {
 *       use(data);
 *     } finally {
 *       rwl.readLock().unlock();
 *     }
 *   }
 * }}</pre>
 *
 * ReentrantReadWriteLocks可用于在某些类型的集合的某些用途中改善并发性。
 * 只有当集合预期很大，读线程比写线程访问的线程多，并且需要的操作开销超过同步开销时，这样做才有价值。
 * 例如，这里有一个使用TreeMap的类，它预计会很大，并且可以并发访问。
 *
 *  <pre> {@code
 * class RWDictionary {
 *   private final Map<String, Data> m = new TreeMap<String, Data>();
 *   private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
 *   private final Lock r = rwl.readLock();
 *   private final Lock w = rwl.writeLock();
 *
 *   public Data get(String key) {
 *     r.lock();
 *     try { return m.get(key); }
 *     finally { r.unlock(); }
 *   }
 *   public String[] allKeys() {
 *     r.lock();
 *     try { return m.keySet().toArray(); }
 *     finally { r.unlock(); }
 *   }
 *   public Data put(String key, Data value) {
 *     w.lock();
 *     try { return m.put(key, value); }
 *     finally { w.unlock(); }
 *   }
 *   public void clear() {
 *     w.lock();
 *     try { m.clear(); }
 *     finally { w.unlock(); }
 *   }
 * }}</pre>
 *
 * <h3>Implementation Notes</h3>
 *
 * <p>该锁最多支持65535个递归写锁和65535个读锁。
 * 试图超过这些限制将导致锁定方法抛出错误。
 *
 * @since 1.5
 * @author Doug Lea
 */
public class ReentrantReadWriteLock
        implements ReadWriteLock, java.io.Serializable {
    private static final long serialVersionUID = -6992448646407690164L;
    /** 提供读锁的内部类 */
    private final ReentrantReadWriteLock.ReadLock readerLock;
    /** 提供写锁的内部类 */
    private final ReentrantReadWriteLock.WriteLock writerLock;
    /** 执行所有同步操作 */
    final Sync sync;

    /**
     * 使用默认(非公平)排序属性创建一个新的ReentrantReadWriteLock。
     */
    public ReentrantReadWriteLock() {
        this(false);
    }

    /**
     * 使用给定的公平属性创建一个新的ReentrantReadWriteLock。
     *
     * @param fair {@code true} if this lock should use a fair ordering policy
     */
    public ReentrantReadWriteLock(boolean fair) {
        sync = fair ? new FairSync() : new NonfairSync();
        readerLock = new ReadLock(this);
        writerLock = new WriteLock(this);
    }

    public ReentrantReadWriteLock.WriteLock writeLock() { return writerLock; }
    public ReentrantReadWriteLock.ReadLock  readLock()  { return readerLock; }

    /**
     * ReentrantReadWriteLock的同步实现。子类分为公平版本和不公平版本。
     */
    abstract static class Sync extends AbstractQueuedSynchronizer {
        private static final long serialVersionUID = 6317671515068378041L;

        /*
         * 读取和写入，提取常量和函数。
         * Lock state在逻辑上分为两个unsigned short:较低的表示排他(写入)锁保持计数，
         * 较高的表示共享(读取)锁保持计数。
         */

        static final int SHARED_SHIFT   = 16;
        static final int SHARED_UNIT    = (1 << SHARED_SHIFT);
        static final int MAX_COUNT      = (1 << SHARED_SHIFT) - 1;
        static final int EXCLUSIVE_MASK = (1 << SHARED_SHIFT) - 1;
        // c有32位 aaaabbbb
        // aaaa代表读，bbbb代表写
        /** 返回在count中表示的共享持有数，相当于c/  */
        static int sharedCount(int c)    { return c >>> SHARED_SHIFT; }
        /** 返回count中表示的独占持有数  */
        static int exclusiveCount(int c) { return c & EXCLUSIVE_MASK; }

        /**
         * 每个线程读取保持计数的计数器。
         * 作为ThreadLocal维护;缓存在cachedHoldCounter
         */
        static final class HoldCounter {
            int count = 0;
            // 使用id，而不是引用，以避免垃圾保留
            final long tid = getThreadId(Thread.currentThread());
        }

        /**
         * ThreadLocal子类。为了反序列化机制，最容易显式定义。
         */
        static final class ThreadLocalHoldCounter
            extends ThreadLocal<HoldCounter> {
            public HoldCounter initialValue() {
                return new HoldCounter();
            }
        }

        /**
         * 当前线程持有的可重入读锁的数量。
         * 仅在构造函数和readObject中初始化。当线程的读保持计数下降到0时删除。
         * 对readHolds调用get的时候，调用initialValue，返回一个新的HoldCounter实例。
         * 内部count为0，tid为当前线程的id
         */
        private transient ThreadLocalHoldCounter readHolds;

        /**
         * 成功获取readLock的最后一个线程的保持计数。
         * 在通常情况下，下一个要释放的线程是最后一个需要获取的线程，这样可以节省线程本地查找。
         * 这是非volatile的，因为它只是作为一种启发式使用，并且对于线程缓存是非常好的。
         *
         * <p>可以比它缓存read hold计数的线程更长寿，但通过不保留对该线程的引用来避免垃圾保留。
         *
         * <p>通过良性的数据竞争访问;依赖于内存模型的final字段和out-of-thin-air保证。
         */
        private transient HoldCounter cachedHoldCounter;

        /**
         * firstReader是第一个获得读锁的线程。firstReaderHoldCount是firstReader的保持计数。
         *
         * <p>更准确地说，firstReader是最后一次将共享计数从0修改为1的唯一线程，
         * 并且从那以后一直没有释放读取锁;如果没有这样的线程，则为null。
         *
         * <p>因为tryReleaseShared设置它为null，除非线程在没有放弃读锁的情况下终止，否则不会导致垃圾保留。
         *
         * <p>通过良性的数据竞争访问;依赖于内存模型对引用的out-of-thin-air保证。
         *
         * <p>这使得跟踪无争用的readlock的读锁非常便宜。
         */
        private transient Thread firstReader = null;
        private transient int firstReaderHoldCount;

        Sync() {
            readHolds = new ThreadLocalHoldCounter();
            setState(getState()); // 确保readHolds的可见性
        }

        /*
         * 对于公平锁和非公平锁，获取锁和释放锁使用相同的代码，
         * 但不同的是，当队列非空时，它们是否/如何允许抢占锁。
         */

        /**
         * 如果当前线程在试图获取读锁时，或者有资格这样做，
         * 因为策略是为了超过其他等待的线程而阻塞，则返回true。
         */
        abstract boolean readerShouldBlock();

        /**
         * 如果当前线程在试图获取写锁时，或者有资格这样做，
         * 因为策略是为了超过其他等待的线程而阻塞，则返回true。
         */
        abstract boolean writerShouldBlock();

        /*
         * 请注意，tryRelease和tryAcquire可以被Conditions调用。
         * 因此，它们的参数可能同时包含read和write holds，这些持有在条件等待和tryAcquire中重新建立过程中全部释放。
         */

        protected final boolean tryRelease(int releases) {
            if (!isHeldExclusively())
                throw new IllegalMonitorStateException();
            int nextc = getState() - releases;
            // 如果独占数为0，设置线程为null，并返回true
            boolean free = exclusiveCount(nextc) == 0;
            if (free)
                setExclusiveOwnerThread(null);
            setState(nextc);
            return free;
        }

        protected final boolean tryAcquire(int acquires) {
            /*
             * 介绍:
             * 1. 如果读计数非零或写计数非零，并且所有者是另一个线程，则失败。
             * 2. 如果count饱和，则失败。(这只会发生在count已经是非零的情况下。)
             * 3. 否则，如果这个线程是可重入获取的，或者队列策略允许它，
             *    那么它就有资格获得锁。如果是，更新状态并设置owner。
             */
            Thread current = Thread.currentThread();
            int c = getState();
            int w = exclusiveCount(c);
            // c不为0，w或者读，至少有一个锁
            if (c != 0) {
                // (Note: if c != 0 and w == 0 then shared count != 0)
            	// w为0，代表有读锁，不能获得写锁
            	// w不为0，当前写锁的线程不是current，不能获得写锁
                if (w == 0 || current != getExclusiveOwnerThread())
                    return false;
                // count饱和
                if (w + exclusiveCount(acquires) > MAX_COUNT)
                    throw new Error("Maximum lock count exceeded");
                // 重入获得锁
                setState(c + acquires);
                return true;
            }
            // c为0，没有读写锁
            // 如果写锁不应该阻塞，cas设置状态失败，返回false
            // 如果写锁要阻塞，返回false
            if (writerShouldBlock() ||
                !compareAndSetState(c, c + acquires))
                return false;
            // cas设置状态成功，设置独占线程
            setExclusiveOwnerThread(current);
            return true;
        }

        protected final boolean tryReleaseShared(int unused) {
            Thread current = Thread.currentThread();
            if (firstReader == current) {
                // assert firstReaderHoldCount > 0;
            	// 如果当前线程是firstReader，而且只剩1，设置firstReader为null
                if (firstReaderHoldCount == 1)
                    firstReader = null;
                else
                    firstReaderHoldCount--;
            } else {
            	// 相当于每一个读线程有一个threadLocal，代表该线程读锁的占有数，对它进行操作
            	// 得到当前线程的HoldCounter
                HoldCounter rh = cachedHoldCounter;
                if (rh == null || rh.tid != getThreadId(current))
                    rh = readHolds.get();
                // 视情况，删除HoldCounter
                int count = rh.count;
                if (count <= 1) {
                    readHolds.remove();
                    if (count <= 0)
                        throw unmatchedUnlockException();
                }
                --rh.count;
            }
            for (;;) {
            	// 不断cas状态
                int c = getState();
                int nextc = c - SHARED_UNIT;
                if (compareAndSetState(c, nextc))
                    // 状态改完后，返回状态是否为0
                	// 释放读锁对读取器没有影响，但是如果读锁和写锁都是空闲的，它可以允许正在等待的写器继续操作。
                    return nextc == 0;
            }
        }

        private IllegalMonitorStateException unmatchedUnlockException() {
            return new IllegalMonitorStateException(
                "attempt to unlock read lock, not locked by current thread");
        }

        protected final int tryAcquireShared(int unused) {
            /*
             * 介绍:
             * 1. 如果写锁被另一个线程持有，则失败。
             * 2. 否则，这个线程符合锁wrt状态，因此询问它是否应该因为队列策略而阻塞。
             *    如果没有，尝试通过CASing状态和更新计数来授予。
             *    注意，该步骤不检查重入的获取，这被推迟到完整版本，以避免在更典型的非重入情况下必须检查持有计数。
             *    
             * 3. 如果步骤2失败是因为线程显然不符合条件，或者CAS失败或计数饱和，则使用完整的重试循环链接到版本。
             */
            Thread current = Thread.currentThread();
            int c = getState();
            if (exclusiveCount(c) != 0 &&
                getExclusiveOwnerThread() != current)
                return -1;
            int r = sharedCount(c);
            // 先判断是否要阻塞，然后尝试设置状态
            if (!readerShouldBlock() &&
                r < MAX_COUNT &&
                compareAndSetState(c, c + SHARED_UNIT)) {
                if (r == 0) {
                	// 如果一开始没有读锁，设置firstReader
                    firstReader = current;
                    firstReaderHoldCount = 1;
                } else if (firstReader == current) {
                	// 有读锁，而且是firstReader
                    firstReaderHoldCount++;
                } else {
                	// 有读锁，但不是firstReader，设置readHolds
                    HoldCounter rh = cachedHoldCounter;
                    if (rh == null || rh.tid != getThreadId(current))
                        cachedHoldCounter = rh = readHolds.get();
                    else if (rh.count == 0)
                        readHolds.set(rh);
                    rh.count++;
                }
                // 返回1
                return 1;
            }
            // 之前没有获得读锁的，全量尝试
            return fullTryAcquireShared(current);
        }

        /**
         * 完整版本的获取读取，处理在tryAcquireShared没有解决的CAS miss和重入读取，。
         */
        final int fullTryAcquireShared(Thread current) {
            /*
             * 这段代码与tryAcquireShared中的代码相比有些多余，但总体上更简单，
             * 因为它没有让tryAcquireShared与重试和惰性读取持有计数之间的交互复杂化。
             */
            HoldCounter rh = null;
            for (;;) {
                int c = getState();
                if (exclusiveCount(c) != 0) {
                    if (getExclusiveOwnerThread() != current)
                        return -1;
                    // 否则，我们持有排他锁;这里的阻塞会导致死锁。
                } else if (readerShouldBlock()) {
                    // 确保我们没有以重入的方式获取读锁
                    if (firstReader == current) {
                        // assert firstReaderHoldCount > 0;
                    } else {
                        if (rh == null) {
                            rh = cachedHoldCounter;
                            if (rh == null || rh.tid != getThreadId(current)) {
                                rh = readHolds.get();
                                if (rh.count == 0)
                                    readHolds.remove();
                            }
                        }
                        if (rh.count == 0)
                            return -1;
                    }
                }
                if (sharedCount(c) == MAX_COUNT)
                    throw new Error("Maximum lock count exceeded");
                if (compareAndSetState(c, c + SHARED_UNIT)) {
                    if (sharedCount(c) == 0) {
                        firstReader = current;
                        firstReaderHoldCount = 1;
                    } else if (firstReader == current) {
                        firstReaderHoldCount++;
                    } else {
                        if (rh == null)
                            rh = cachedHoldCounter;
                        if (rh == null || rh.tid != getThreadId(current))
                            rh = readHolds.get();
                        else if (rh.count == 0)
                            readHolds.set(rh);
                        rh.count++;
                        cachedHoldCounter = rh; // cache for release
                    }
                    return 1;
                }
            }
        }

        /**
         * 为写执行tryLock，在两种模式下都启用抢占。
         * 除了缺少对writerShouldBlock的调用之外，这与tryAcquire的效果是相同的。
         */
        final boolean tryWriteLock() {
            Thread current = Thread.currentThread();
            int c = getState();
            if (c != 0) {
                int w = exclusiveCount(c);
                // w为0，代表有读锁，没有写锁，不能获取
                if (w == 0 || current != getExclusiveOwnerThread())
                    return false;
                if (w == MAX_COUNT)
                    throw new Error("Maximum lock count exceeded");
            }
            if (!compareAndSetState(c, c + 1))
                return false;
            setExclusiveOwnerThread(current);
            return true;
        }

        /**
         * 执行tryLock读取，在两种模式下启用barging。
         * 除了缺少对readerShouldBlock的调用之外，这实际上与tryAcquireShared是相同的。
         */
        final boolean tryReadLock() {
            Thread current = Thread.currentThread();
            for (;;) {
                int c = getState();
                if (exclusiveCount(c) != 0 &&
                    getExclusiveOwnerThread() != current)
                    return false;
                int r = sharedCount(c);
                if (r == MAX_COUNT)
                    throw new Error("Maximum lock count exceeded");
                if (compareAndSetState(c, c + SHARED_UNIT)) {
                    if (r == 0) {
                        firstReader = current;
                        firstReaderHoldCount = 1;
                    } else if (firstReader == current) {
                        firstReaderHoldCount++;
                    } else {
                        HoldCounter rh = cachedHoldCounter;
                        if (rh == null || rh.tid != getThreadId(current))
                            cachedHoldCounter = rh = readHolds.get();
                        else if (rh.count == 0)
                            readHolds.set(rh);
                        rh.count++;
                    }
                    return true;
                }
            }
        }

        protected final boolean isHeldExclusively() {
            // 虽然我们通常必须在所有者之前读取状态，但我们不需要这样做来检查当前线程是否为所有者
            return getExclusiveOwnerThread() == Thread.currentThread();
        }

        // 转发给外部类的方法

        final ConditionObject newCondition() {
            return new ConditionObject();
        }

        final Thread getOwner() {
            // 必须在所有者之前读取状态以确保内存的一致性
            return ((exclusiveCount(getState()) == 0) ?
                    null :
                    getExclusiveOwnerThread());
        }

        final int getReadLockCount() {
            return sharedCount(getState());
        }

        final boolean isWriteLocked() {
            return exclusiveCount(getState()) != 0;
        }

        final int getWriteHoldCount() {
            return isHeldExclusively() ? exclusiveCount(getState()) : 0;
        }

        /** 返回当前线程的读锁占有数
         * @return
         */
        final int getReadHoldCount() {
            if (getReadLockCount() == 0)
                return 0;

            Thread current = Thread.currentThread();
            if (firstReader == current)
                return firstReaderHoldCount;

            HoldCounter rh = cachedHoldCounter;
            if (rh != null && rh.tid == getThreadId(current))
                return rh.count;

            int count = readHolds.get().count;
            if (count == 0) readHolds.remove();
            return count;
        }

        /**
         * 从流中重新构造实例(即反序列化)。
         */
        private void readObject(java.io.ObjectInputStream s)
            throws java.io.IOException, ClassNotFoundException {
            s.defaultReadObject();
            readHolds = new ThreadLocalHoldCounter();
            setState(0); // 重置为解锁状态
        }

        final int getCount() { return getState(); }
    }

    /**
     * Sync的非公平版本
     */
    static final class NonfairSync extends Sync {
        private static final long serialVersionUID = -8159625535654395037L;
        final boolean writerShouldBlock() {
            return false; // 写的线程总是能抢占
        }
        final boolean readerShouldBlock() {
            /* 作为一种避免无限写线程饥饿的启发式方法，
             * 如果暂时出现在队列头的线程(如果存在的话)是正在等待的写线程，则阻塞。
             * 这只是一种概率效应，因为如果在其他已启用的、
             * 尚未从队列中耗尽的读取器后面有一个正在等待的写入器，那么新的读取器将不会阻塞。
             */
            return apparentlyFirstQueuedIsExclusive();
        }
    }

    /**
     * Sync的公平版本
     */
    static final class FairSync extends Sync {
        private static final long serialVersionUID = -2274990926593161451L;
        final boolean writerShouldBlock() {
            return hasQueuedPredecessors();
        }
        final boolean readerShouldBlock() {
            return hasQueuedPredecessors();
        }
    }

    /**
     * {@link ReentrantReadWriteLock#readLock}返回的锁
     */
    public static class ReadLock implements Lock, java.io.Serializable {
        private static final long serialVersionUID = -5992448646407690164L;
        // sync是ReentrantReadWriteLock的sync
        private final Sync sync;

        /**
         * 子类使用的构造函数
         *
         * @param lock the outer lock object
         * @throws NullPointerException if the lock is null
         */
        protected ReadLock(ReentrantReadWriteLock lock) {
            sync = lock.sync;
        }

        /**
         * 获取读锁。
         *
         * <p>如果写锁没有被其他线程持有，则获取读锁并立即返回。
         *
         * <p>如果写锁被另一个线程持有，那么当前线程在线程调度中会被禁用，并处于休眠状态，直到获得读锁。
         */
        public void lock() {
            sync.acquireShared(1);
        }

        /**
         * 除非当前线程被中断，否则获取读锁。
         *
         * <p>如果写锁没有被其他线程持有，则获取读锁并立即返回。
         *
         * <p>如果写锁被另一个线程持有，那么当前线程就会因为
         * 线程调度的目的而被禁用，并处于休眠状态，直到有以下两种情况发生:
         *
         * <ul>
         *
         * <li>读锁是由当前线程获取的;或
         *
         * <li>其他线程中断当前线程。
         *
         * </ul>
         *
         * <p>如果当前线程:
         *
         * <ul>
         *
         * <li>在进入该方法时设置中断状态;或
         *
         * <li>在获取读锁时被中断，
         *
         * </ul>
         *
         * 然后抛出InterruptedException，并清除当前线程的中断状态。
         *
         * <p>在这个实现中，因为这个方法是一个显式中断点，
         * 所以优先响应中断，而不是正常的或重入的锁获取。
         *
         * @throws InterruptedException if the current thread is interrupted
         */
        public void lockInterruptibly() throws InterruptedException {
            sync.acquireSharedInterruptibly(1);
        }

        /**
         * 只有在调用时写锁没有被另一个线程持有时才获得读锁。
         *
         * <p>如果写锁没有被其他线程持有，则获取读锁，并立即返回值为true。
         * 即使这个锁已经被设置为使用了公平排序策略，
         * 调用tryLock()将立即获得读锁，如果它是可用的，无论其他线程是否正在等待读锁。
         * 这种“冲撞”行为在某些情况下是有用的，即使它破坏了公平。
         * 如果您想为这个锁遵守公平性设置，那么使用tryLock(0, TimeUnit.SECONDS)，它几乎是等价的(它也检测中断)。
         *
         * <p>如果写锁被另一个线程持有，那么这个方法将立即返回值为false。
         *
         * @return {@code true} if the read lock was acquired
         */
        public boolean tryLock() {
            return sync.tryReadLock();
        }

        /**
         * 如果在给定的等待时间内其他线程没有持有写锁，并且当前线程没有被中断，则获取读锁。
         *
         * <p>如果写锁没有被其他线程持有，则获取读锁，并立即返回值为true。
         * 如果该锁被设置为使用公平排序策略，那么如果有其他线程正在等待锁，则不会获得可用的锁。
         * 这与tryLock()方法相反。如果你想要一个计时的tryLock的抢占，
         * 它不允许在一个公平锁上进行操作，那么可以将计时和非计时的形式组合在一起:
         *
         *  <pre> {@code
         * if (lock.tryLock() ||
         *     lock.tryLock(timeout, unit)) {
         *   ...
         * }}</pre>
         *
         * <p>如果写锁被另一个线程持有，那么当前线程在线程调度中会被禁用，
         * 并处于休眠状态，直到以下三种情况之一发生:
         *
         * <ul>
         *
         * <li>读锁是由当前线程获取的;或
         *
         * <li>其他线程中断当前线程;或
         *
         * <li>经过指定的等待时间。
         *
         * </ul>
         *
         * <p>如果获得了读锁，则返回值true。
         *
         * <p>如果当前线程:
         *
         * <ul>
         *
         * <li>在进入该方法时设置中断状态;或
         *
         * <li>在获取读锁时被中断，
         *
         * </ul> 然后抛出InterruptedException，并清除当前线程的中断状态。
         *
         * <p>如果指定的等待时间过去了，则返回值false。
         * 如果时间小于等于0，该方法将根本不等待。
         *
         * <p>在这个实现中，由于这个方法是一个显式中断点，优先考虑响应中断，
         * 而不是正常或重入的锁获取，以及报告等待时间的推移。
         *
         * @param timeout the time to wait for the read lock
         * @param unit the time unit of the timeout argument
         * @return {@code true} if the read lock was acquired
         * @throws InterruptedException if the current thread is interrupted
         * @throws NullPointerException if the time unit is null
         */
        public boolean tryLock(long timeout, TimeUnit unit)
                throws InterruptedException {
            return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
        }

        /**
         * 试图释放此锁。
         *
         * <p>如果读取器的数量现在为零，那么锁可以用于写锁尝试。
         */
        public void unlock() {
            sync.releaseShared(1);
        }

        /**
         * 抛出UnsupportedOperationException，因为readlock不支持条件。
         *
         * @throws UnsupportedOperationException always
         */
        public Condition newCondition() {
            throw new UnsupportedOperationException();
        }

        /**
         * 返回标识此锁及其锁状态的字符串。括号中的状态包括字符串“Read locks =”，后面跟着持有的读锁的数量。
         *
         * @return a string identifying this lock, as well as its lock state
         */
        public String toString() {
            int r = sync.getReadLockCount();
            return super.toString() +
                "[Read locks = " + r + "]";
        }
    }

    /**
     * {@link ReentrantReadWriteLock#writeLock}返回的锁
     */
    public static class WriteLock implements Lock, java.io.Serializable {
        private static final long serialVersionUID = -4992448646407690164L;
        private final Sync sync;

        /**
         * 子类使用的构造函数
         *
         * @param lock the outer lock object
         * @throws NullPointerException if the lock is null
         */
        protected WriteLock(ReentrantReadWriteLock lock) {
            sync = lock.sync;
        }

        /**
         * 获取写锁。
         *
         * <p>如果读锁和写锁都没有被另一个线程持有，则获取写锁，并立即返回，将写锁持有次数设置为1。
         *
         * <p>如果当前线程已经持有写锁，则保持计数加1，该方法立即返回。
         *
         * <p>如果锁被另一个线程持有，那么为了线程调度的目的，当前线程将被禁用，
         * 并处于休眠状态，直到获得写锁，此时写锁持有计数被设置为1。
         */
        public void lock() {
            sync.acquire(1);
        }

        /**
         * Acquires the write lock unless the current thread is
         * {@linkplain Thread#interrupt interrupted}.
         *
         * <p>Acquires the write lock if neither the read nor write lock
         * are held by another thread
         * and returns immediately, setting the write lock hold count to
         * one.
         *
         * <p>If the current thread already holds this lock then the
         * hold count is incremented by one and the method returns
         * immediately.
         *
         * <p>If the lock is held by another thread then the current
         * thread becomes disabled for thread scheduling purposes and
         * lies dormant until one of two things happens:
         *
         * <ul>
         *
         * <li>The write lock is acquired by the current thread; or
         *
         * <li>Some other thread {@linkplain Thread#interrupt interrupts}
         * the current thread.
         *
         * </ul>
         *
         * <p>If the write lock is acquired by the current thread then the
         * lock hold count is set to one.
         *
         * <p>If the current thread:
         *
         * <ul>
         *
         * <li>has its interrupted status set on entry to this method;
         * or
         *
         * <li>is {@linkplain Thread#interrupt interrupted} while
         * acquiring the write lock,
         *
         * </ul>
         *
         * then {@link InterruptedException} is thrown and the current
         * thread's interrupted status is cleared.
         *
         * <p>In this implementation, as this method is an explicit
         * interruption point, preference is given to responding to
         * the interrupt over normal or reentrant acquisition of the
         * lock.
         *
         * @throws InterruptedException if the current thread is interrupted
         */
        public void lockInterruptibly() throws InterruptedException {
            sync.acquireInterruptibly(1);
        }

        /**
         * Acquires the write lock only if it is not held by another thread
         * at the time of invocation.
         *
         * <p>Acquires the write lock if neither the read nor write lock
         * are held by another thread
         * and returns immediately with the value {@code true},
         * setting the write lock hold count to one. Even when this lock has
         * been set to use a fair ordering policy, a call to
         * {@code tryLock()} <em>will</em> immediately acquire the
         * lock if it is available, whether or not other threads are
         * currently waiting for the write lock.  This &quot;barging&quot;
         * behavior can be useful in certain circumstances, even
         * though it breaks fairness. If you want to honor the
         * fairness setting for this lock, then use {@link
         * #tryLock(long, TimeUnit) tryLock(0, TimeUnit.SECONDS) }
         * which is almost equivalent (it also detects interruption).
         *
         * <p>If the current thread already holds this lock then the
         * hold count is incremented by one and the method returns
         * {@code true}.
         *
         * <p>If the lock is held by another thread then this method
         * will return immediately with the value {@code false}.
         *
         * @return {@code true} if the lock was free and was acquired
         * by the current thread, or the write lock was already held
         * by the current thread; and {@code false} otherwise.
         */
        public boolean tryLock( ) {
            return sync.tryWriteLock();
        }

        /**
         * Acquires the write lock if it is not held by another thread
         * within the given waiting time and the current thread has
         * not been {@linkplain Thread#interrupt interrupted}.
         *
         * <p>Acquires the write lock if neither the read nor write lock
         * are held by another thread
         * and returns immediately with the value {@code true},
         * setting the write lock hold count to one. If this lock has been
         * set to use a fair ordering policy then an available lock
         * <em>will not</em> be acquired if any other threads are
         * waiting for the write lock. This is in contrast to the {@link
         * #tryLock()} method. If you want a timed {@code tryLock}
         * that does permit barging on a fair lock then combine the
         * timed and un-timed forms together:
         *
         *  <pre> {@code
         * if (lock.tryLock() ||
         *     lock.tryLock(timeout, unit)) {
         *   ...
         * }}</pre>
         *
         * <p>If the current thread already holds this lock then the
         * hold count is incremented by one and the method returns
         * {@code true}.
         *
         * <p>If the lock is held by another thread then the current
         * thread becomes disabled for thread scheduling purposes and
         * lies dormant until one of three things happens:
         *
         * <ul>
         *
         * <li>The write lock is acquired by the current thread; or
         *
         * <li>Some other thread {@linkplain Thread#interrupt interrupts}
         * the current thread; or
         *
         * <li>The specified waiting time elapses
         *
         * </ul>
         *
         * <p>If the write lock is acquired then the value {@code true} is
         * returned and the write lock hold count is set to one.
         *
         * <p>If the current thread:
         *
         * <ul>
         *
         * <li>has its interrupted status set on entry to this method;
         * or
         *
         * <li>is {@linkplain Thread#interrupt interrupted} while
         * acquiring the write lock,
         *
         * </ul>
         *
         * then {@link InterruptedException} is thrown and the current
         * thread's interrupted status is cleared.
         *
         * <p>If the specified waiting time elapses then the value
         * {@code false} is returned.  If the time is less than or
         * equal to zero, the method will not wait at all.
         *
         * <p>In this implementation, as this method is an explicit
         * interruption point, preference is given to responding to
         * the interrupt over normal or reentrant acquisition of the
         * lock, and over reporting the elapse of the waiting time.
         *
         * @param timeout the time to wait for the write lock
         * @param unit the time unit of the timeout argument
         *
         * @return {@code true} if the lock was free and was acquired
         * by the current thread, or the write lock was already held by the
         * current thread; and {@code false} if the waiting time
         * elapsed before the lock could be acquired.
         *
         * @throws InterruptedException if the current thread is interrupted
         * @throws NullPointerException if the time unit is null
         */
        public boolean tryLock(long timeout, TimeUnit unit)
                throws InterruptedException {
            return sync.tryAcquireNanos(1, unit.toNanos(timeout));
        }

        /**
         * Attempts to release this lock.
         *
         * <p>If the current thread is the holder of this lock then
         * the hold count is decremented. If the hold count is now
         * zero then the lock is released.  If the current thread is
         * not the holder of this lock then {@link
         * IllegalMonitorStateException} is thrown.
         *
         * @throws IllegalMonitorStateException if the current thread does not
         * hold this lock
         */
        public void unlock() {
            sync.release(1);
        }

        /**
         * 返回与此锁实例一起使用的条件实例。
         * 
         * <p>当与内置监视锁一起使用时，返回的Condition实例
         * 支持与对象监视器方法(wait、notify和notifyAll)相同的用法。
         *
         * <ul>
         *
         * <li>当任何条件方法被调用时，如果这个写锁没有被持有，
         * 那么抛出一个IllegalMonitorStateException。(读锁独立于写锁，所以不会被检查或影响。
         * 然而，当当前线程也获得了读锁时，调用条件等待方法本质上
         * 总是一个错误，因为其他可以解除阻塞的线程将无法获得写锁。)
         *
         * <li>当条件等待方法被调用时，写锁被释放，在它们返回之前，
         * 写锁被重新获取，锁持有数恢复到该方法被调用时的状态。
         *
         * <li>如果一个线程在等待时被中断，那么等待将终止，
         * 并抛出InterruptedException异常，线程的中断状态将被清除。
         *
         * <li> 等待线程以FIFO顺序发出信号。
         *
         * <li>从等待方法中返回的线程重新获取锁的顺序与初始获取锁的线程相同，
         * 这在默认情况下没有指定，但是对于公平锁，对那些等待时间最长的线程优先。
         *
         * </ul>
         *
         * @return the Condition object
         */
        public Condition newCondition() {
            return sync.newCondition();
        }

        /**
         * 返回标识此锁及其锁状态的字符串。
         * 括号中的状态包括字符串“Unlocked”或字符串“Locked by”，后面跟着所属线程的名称。
         *
         * @return a string identifying this lock, as well as its lock state
         */
        public String toString() {
            Thread o = sync.getOwner();
            return super.toString() + ((o == null) ?
                                       "[Unlocked]" :
                                       "[Locked by thread " + o.getName() + "]");
        }

        /**
         * 查询当前线程是否持有此写锁。与ReentrantReadWriteLock.isWriteLockedByCurrentThread的效果相同。
         *
         * @return {@code true} if the current thread holds this lock and
         *         {@code false} otherwise
         * @since 1.6
         */
        public boolean isHeldByCurrentThread() {
            return sync.isHeldExclusively();
        }

        /**
         * 查询当前线程对这个写锁的持有数。一个线程对每个不匹配解锁操作的锁操作都持有一个锁。
         *
         * @return the number of holds on this lock by the current thread,
         *         or zero if this lock is not held by the current thread
         * @since 1.6
         */
        public int getHoldCount() {
            return sync.getWriteHoldCount();
        }
    }

    // 仪表和地位

    /**
     * 如果该锁的公平性设置为true则返回true。
     *
     * @return {@code true} if this lock has fairness set true
     */
    public final boolean isFair() {
        return sync instanceof FairSync;
    }

    /**
     * 返回当前拥有写锁的线程，如果没有，则返回null。
     * 当该方法被非所有者线程调用时，返回值反映当前锁状态的最大努力近似值。
     * 例如，即使有线程正在试图获取锁，但还没有这样做，所有者也可能暂时为空。
     * 这种方法是为了便于构造提供更广泛的锁监控设施的子类。
     *
     * @return the owner, or {@code null} if not owned
     */
    protected Thread getOwner() {
        return sync.getOwner();
    }

    /**
     * Queries the number of read locks held for this lock. This
     * method is designed for use in monitoring system state, not for
     * synchronization control.
     * @return the number of read locks held
     */
    public int getReadLockCount() {
        return sync.getReadLockCount();
    }

    /**
     * Queries if the write lock is held by any thread. This method is
     * designed for use in monitoring system state, not for
     * synchronization control.
     *
     * @return {@code true} if any thread holds the write lock and
     *         {@code false} otherwise
     */
    public boolean isWriteLocked() {
        return sync.isWriteLocked();
    }

    /**
     * Queries if the write lock is held by the current thread.
     *
     * @return {@code true} if the current thread holds the write lock and
     *         {@code false} otherwise
     */
    public boolean isWriteLockedByCurrentThread() {
        return sync.isHeldExclusively();
    }

    /**
     * Queries the number of reentrant write holds on this lock by the
     * current thread.  A writer thread has a hold on a lock for
     * each lock action that is not matched by an unlock action.
     *
     * @return the number of holds on the write lock by the current thread,
     *         or zero if the write lock is not held by the current thread
     */
    public int getWriteHoldCount() {
        return sync.getWriteHoldCount();
    }

    /**
     * Queries the number of reentrant read holds on this lock by the
     * current thread.  A reader thread has a hold on a lock for
     * each lock action that is not matched by an unlock action.
     *
     * @return the number of holds on the read lock by the current thread,
     *         or zero if the read lock is not held by the current thread
     * @since 1.6
     */
    public int getReadHoldCount() {
        return sync.getReadHoldCount();
    }

    /**
     * Returns a collection containing threads that may be waiting to
     * acquire the write lock.  Because the actual set of threads may
     * change dynamically while constructing this result, the returned
     * collection is only a best-effort estimate.  The elements of the
     * returned collection are in no particular order.  This method is
     * designed to facilitate construction of subclasses that provide
     * more extensive lock monitoring facilities.
     *
     * @return the collection of threads
     */
    protected Collection<Thread> getQueuedWriterThreads() {
        return sync.getExclusiveQueuedThreads();
    }

    /**
     * Returns a collection containing threads that may be waiting to
     * acquire the read lock.  Because the actual set of threads may
     * change dynamically while constructing this result, the returned
     * collection is only a best-effort estimate.  The elements of the
     * returned collection are in no particular order.  This method is
     * designed to facilitate construction of subclasses that provide
     * more extensive lock monitoring facilities.
     *
     * @return the collection of threads
     */
    protected Collection<Thread> getQueuedReaderThreads() {
        return sync.getSharedQueuedThreads();
    }

    /**
     * Queries whether any threads are waiting to acquire the read or
     * write lock. Note that because cancellations may occur at any
     * time, a {@code true} return does not guarantee that any other
     * thread will ever acquire a lock.  This method is designed
     * primarily for use in monitoring of the system state.
     *
     * @return {@code true} if there may be other threads waiting to
     *         acquire the lock
     */
    public final boolean hasQueuedThreads() {
        return sync.hasQueuedThreads();
    }

    /**
     * Queries whether the given thread is waiting to acquire either
     * the read or write lock. Note that because cancellations may
     * occur at any time, a {@code true} return does not guarantee
     * that this thread will ever acquire a lock.  This method is
     * designed primarily for use in monitoring of the system state.
     *
     * @param thread the thread
     * @return {@code true} if the given thread is queued waiting for this lock
     * @throws NullPointerException if the thread is null
     */
    public final boolean hasQueuedThread(Thread thread) {
        return sync.isQueued(thread);
    }

    /**
     * Returns an estimate of the number of threads waiting to acquire
     * either the read or write lock.  The value is only an estimate
     * because the number of threads may change dynamically while this
     * method traverses internal data structures.  This method is
     * designed for use in monitoring of the system state, not for
     * synchronization control.
     *
     * @return the estimated number of threads waiting for this lock
     */
    public final int getQueueLength() {
        return sync.getQueueLength();
    }

    /**
     * Returns a collection containing threads that may be waiting to
     * acquire either the read or write lock.  Because the actual set
     * of threads may change dynamically while constructing this
     * result, the returned collection is only a best-effort estimate.
     * The elements of the returned collection are in no particular
     * order.  This method is designed to facilitate construction of
     * subclasses that provide more extensive monitoring facilities.
     *
     * @return the collection of threads
     */
    protected Collection<Thread> getQueuedThreads() {
        return sync.getQueuedThreads();
    }

    /**
     * Queries whether any threads are waiting on the given condition
     * associated with the write lock. Note that because timeouts and
     * interrupts may occur at any time, a {@code true} return does
     * not guarantee that a future {@code signal} will awaken any
     * threads.  This method is designed primarily for use in
     * monitoring of the system state.
     *
     * @param condition the condition
     * @return {@code true} if there are any waiting threads
     * @throws IllegalMonitorStateException if this lock is not held
     * @throws IllegalArgumentException if the given condition is
     *         not associated with this lock
     * @throws NullPointerException if the condition is null
     */
    public boolean hasWaiters(Condition condition) {
        if (condition == null)
            throw new NullPointerException();
        if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
            throw new IllegalArgumentException("not owner");
        return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)condition);
    }

    /**
     * Returns an estimate of the number of threads waiting on the
     * given condition associated with the write lock. Note that because
     * timeouts and interrupts may occur at any time, the estimate
     * serves only as an upper bound on the actual number of waiters.
     * This method is designed for use in monitoring of the system
     * state, not for synchronization control.
     *
     * @param condition the condition
     * @return the estimated number of waiting threads
     * @throws IllegalMonitorStateException if this lock is not held
     * @throws IllegalArgumentException if the given condition is
     *         not associated with this lock
     * @throws NullPointerException if the condition is null
     */
    public int getWaitQueueLength(Condition condition) {
        if (condition == null)
            throw new NullPointerException();
        if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
            throw new IllegalArgumentException("not owner");
        return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)condition);
    }

    /**
     * Returns a collection containing those threads that may be
     * waiting on the given condition associated with the write lock.
     * Because the actual set of threads may change dynamically while
     * constructing this result, the returned collection is only a
     * best-effort estimate. The elements of the returned collection
     * are in no particular order.  This method is designed to
     * facilitate construction of subclasses that provide more
     * extensive condition monitoring facilities.
     *
     * @param condition the condition
     * @return the collection of threads
     * @throws IllegalMonitorStateException if this lock is not held
     * @throws IllegalArgumentException if the given condition is
     *         not associated with this lock
     * @throws NullPointerException if the condition is null
     */
    protected Collection<Thread> getWaitingThreads(Condition condition) {
        if (condition == null)
            throw new NullPointerException();
        if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
            throw new IllegalArgumentException("not owner");
        return sync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject)condition);
    }

    /**
     * Returns a string identifying this lock, as well as its lock state.
     * The state, in brackets, includes the String {@code "Write locks ="}
     * followed by the number of reentrantly held write locks, and the
     * String {@code "Read locks ="} followed by the number of held
     * read locks.
     *
     * @return a string identifying this lock, as well as its lock state
     */
    public String toString() {
        int c = sync.getCount();
        int w = Sync.exclusiveCount(c);
        int r = Sync.sharedCount(c);

        return super.toString() +
            "[Write locks = " + w + ", Read locks = " + r + "]";
    }

    /**
     * 返回给定线程的线程id。我们必须直接访问它，
     * 而不是通过Thread.getId()方法，因为getid()不是final，而且已知会被不保留唯一映射的方式覆盖。
     */
    static final long getThreadId(Thread thread) {
        return UNSAFE.getLongVolatile(thread, TID_OFFSET);
    }

    // Unsafe mechanics
    private static final sun.misc.Unsafe UNSAFE;
    private static final long TID_OFFSET;
    static {
        try {
            UNSAFE = sun.misc.Unsafe.getUnsafe();
            Class<?> tk = Thread.class;
            TID_OFFSET = UNSAFE.objectFieldOffset
                (tk.getDeclaredField("tid"));
        } catch (Exception e) {
            throw new Error(e);
        }
    }

}
